const db = uniCloud.database()
import store from '../store/index.js'

async function insert(tableName, data, condition) {
	if (condition) {
		let [unique, msg] = await checkUnique(tableName, condition)
		if (!unique) {
			return [false, '已存在']
		}
	}
	const table = db.collection(tableName)
	let res = await table.add(data)
	if (res.result.errCode == 0) {
		return [true, '']
	}
	return [false, '添加失败']
}
async function getData(tableName, condition) {
	if (condition) {
		let res = await db.collection(tableName).where(condition).get()
		return res.result.data
	} else {
		let res = await db.collection(tableName).get()
		return res.result.data
	}
}
//如果存在，返回假；如果不存在，返回真；
async function checkUnique(tableName, fields) {
	for (let field of fields) {
		let datas = await getData(tableName, field)
		if (datas.length > 0) {
			return [false, datas]
		}
	}
	return [true, '']
}

async function del(tableName, data) {
	const table = db.collection(tableName)
	let res = await table.where(data).remove()
	if (res.result.affectedDocs > 0) {
		return true
	} else {
		return false
	}
}

async function update(tableName, condition, updateData) {
	let [unique, msg] = await checkUnique(tableName, [condition])
	if (!unique) {
		const table = db.collection(tableName)
		let res = await table.where(condition).update(updateData)
		if (res.result.updated > 0) {
			return [res, '更新成功']
		}
	} else {
		let [res, msg] = await insert(tableName, condition, '')
		if (res) {
			return [res, '更新成功']
		}
	}
	return [false, '更新失败']
}

async function getCourse() {
	let res = await db.collection('sportCourse').orderBy('uploadTime desc').get()
	let datas = res.result.data
	if (datas.length > 0) {
		let courses = []
		for (let course of datas) {
			let [fav, data] = await checkUnique('courserCollect', [{
				course_collector: store.getters.getToken,
				course_Id: course._id
			}])
			courses.push({
				id: course._id,
				src: course.course_src,
				fav: !fav,
				name: course.course_name,
				desc: course.course_desc
			})
		}
		return courses
	}
	return []
}

async function getSportKG(condition) {
	let datas
	if (condition) {
		datas = await getData('sportKG', condition)
	} else {
		let res = await db.collection('sportKG').orderBy('uploadTime desc').get()
		datas = res.result.data
	}
	let kgs = []
	if (datas.length > 0) {
		for (let kg of datas) {
			kgs.push({
				id: kg._id,
				img: kg.kg_src,
				title: kg.kg_name,
				info: kg.kg_detail,
				time: new Date(kg.uploadTime).toLocaleString()
			})
		}
		return kgs
	}
	return kgs
}

async function getUserInfo(condition) {
	let datas
	if (condition) {
		datas = await getData('user', condition)
	} else {
		return ''
	}
	if (datas.length > 0) {
		let data = datas[0]
		return [{
			label: 'id',
			value: data._id.slice(0, 10)
		}, {
			label: 'name',
			value: data.user_name
		}, {
			label: 'birthdate',
			value: data.birthdate.split('T')[0].replace(/\//g, '-')
		}, {
			label: 'height',
			value: data.height,
		}, {
			label: 'weigh',
			value: data.weigh
		}, {
			label: 'email',
			value: data.user_email
		}, {
			label: 'account',
			value: data.user_account
		}]
	}
	return ''
}
async function getSportFavCommon() {
	const collect = db.collection('sportCollect').where(`sport_collector=="${store.getters.getToken}"`).getTemp()
	const res = await db.collection(collect, 'sport').get()
	let datas = res.result.data
	let sports = []
	if (datas.length > 0) {
		for (let data of datas) {
			sports.push({
				id: data.sport_Id[0]._id,
				img: data.sport_Id[0].sport_src,
				event: data.sport_Id[0].sport_name,
				calorie: data.sport_Id[0].sport_calorie,
				fav: true
			})

		}
	}
	return sports
}
async function getSportFav(condition) {
	let datas
	if (condition) {
		datas = await getData('sport', condition)
	} else {
		datas = await getData('sport')
	}
	if (datas.length > 0) {
		let event1 = []
		let event2 = []
		let event3 = []
		for (let sport of datas) {
			let [fav, msg] = await checkUnique('sportCollect', [{
				sport_collector: store.getters.getToken,
				sport_Id: sport._id
			}])
			if (fav) {
				continue
			}
			switch (sport.sport_type) {
				case "0":
					event1.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
				case "1":
					event2.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
				case "2":
					event3.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
			}
		}
		return [{
			model: '有氧运动',
			events: event1
		}, {
			model: '力量训练',
			events: event2
		}, {
			model: '柔韧性运动',
			events: event3
		}, ]
	}
	return []
}

async function getSport(condition) {
	let datas
	if (condition) {
		datas = await getData('sport', condition)
	} else {
		datas = await getData('sport')
	}
	if (datas.length > 0) {
		let event1 = []
		let event2 = []
		let event3 = []
		for (let sport of datas) {
			let [fav, msg] = await checkUnique('sportCollect', [{
				sport_collector: store.getters.getToken,
				sport_Id: sport._id
			}])
			switch (parseInt(sport.sport_type)) {
				case 0:
					event1.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
				case 1:
					event2.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
				case 2:
					event3.push({
						id: sport._id,
						img: sport.sport_src,
						event: sport.sport_name,
						calorie: sport.sport_calorie,
						fav: !fav
					});
					break;
			}
		}
		return [{
			model: '有氧运动',
			events: event1
		}, {
			model: '力量训练',
			events: event2
		}, {
			model: '柔韧性运动',
			events: event3
		}, ]
	}
	return []
}


async function getDynamic(condition) {
	let datas
	if (condition) {
		let collect = db.collection('dynamic').where(condition).orderBy('uploadTime desc')
			.getTemp()
		const res = await db.collection(collect, 'user', 'dynamicLike').get()
		datas = res.result.data
	} else {
		let collect = db.collection('dynamic').orderBy('uploadTime desc').getTemp()
		const res = await db.collection(collect, 'user', 'dynamicLike').get()
		datas = res.result.data
	}

	if (datas.length > 0) {
		let dynamicData = []
		for (let dynamic of datas) {

			let isLike = await getData('dynamicLike', {
				dynamic_id: dynamic._id,
				liker: store.getters.getToken
			})
			let commentData = []
			if (dynamic.comments.length > 0) {

				for (let comment of dynamic.comments) {
					let user = await acquireData('user', {
						_id: comment.account
					})
					if (user.length == 0) {
						continue
					}
					commentData.push({
						username: user[0].user_name,
						account: comment.account,
						comment: comment.comment
					})
				}
			}
			dynamicData.push({
				time: dynamic.uploadTime,
				id: dynamic._id._value,
				avatar: dynamic.publisher[0].user_avatar,
				username: dynamic.publisher[0].user_name,
				isLike: isLike.length > 0 ? true : false,
				contentTxt: dynamic.contentTxt,
				contentImg: dynamic.contentImg ? dynamic.contentImg : [],
				comments: commentData,
				likes: dynamic._id.dynamicLike.length,
				label: dynamic.label
			})
		}
		return dynamicData
	}
	return []
}

function tranformDate(time) {
	return time.split('T')[0].replace(/\//g, '-')
}

function getMondayAndSunday(date) {
	date = new Date(date)
	let dayOfWeek = date.getDay()
	if (dayOfWeek == 0) {
		dayOfWeek = 7
	}
	const monday = new Date(date);
	monday.setDate(date.getDate() - dayOfWeek)
	const sunday = new Date(date)
	sunday.setDate(date.getDate() + (8 - dayOfWeek))
	return [tranformDate(monday.toLocaleDateString()), tranformDate(sunday.toLocaleDateString())]
}


function getFirstDayAndLastDayOfMonth(date) {
	const currentDate = new Date(date);
	const month = currentDate.getMonth() + 1;
	const day = currentDate.getDate();

	const firstDayOfMonth = new Date(currentDate.getFullYear(), month - 1, 1);
	const lastDayOfMonth = new Date(currentDate.getFullYear(), month, day);

	return [
		tranformDate(firstDayOfMonth.toLocaleDateString()),
		tranformDate(lastDayOfMonth.toLocaleDateString()),
	]
}

function compareDates(date1Str, date2Str) {
	const date1 = new Date(date1Str)
	const date2 = new Date(date2Str)
	if (date1 - date2 > 0) {
		return 1;
	} else if (date2 - date1 > 0) {
		return -1;
	} else {
		return 0;
	}
}
async function getTrainByDay(time) {
	time = tranformDate(new Date(time).toLocaleDateString())
	let datas = await getData('sportTrain', {
		user_id: store.getters.getToken
	})
	let trainsDatail = []
	if (datas.length > 0) {
		for (let data of datas) {
			if (compareDates(tranformDate(new Date(data.train_start).toLocaleDateString()), time) == 0) {
				let sport = await getData('sport', {
					_id: data.train_id
				})

				if (sport.length > 0) {
					trainsDatail.push({
						img: sport[0].sport_src,
						id: data._id,
						name: sport[0].sport_name,
						calorie: data.train_calorie,
						time: data.train_duration
					})
				}

			}
		}
	}
	return trainsDatail
}
async function getTrainByCondition(condition, time) {
	let trains = []
	if (condition == 0) {
		let datas = await getData('sportTrain', {
			user_id: store.getters.getToken
		})
		if (datas.length > 0) {
			let trans = {}
			for (let data of datas) {
				if (compareDates(tranformDate(new Date(data.train_start).toLocaleDateString()), time) == 0) {
					let sport = await getData('sport', {
						_id: data.train_id
					})

					if (sport.length > 0) {
						if (sport[0].sport_name in trans) {
							trans[sport[0].sport_name] += parseInt(data.train_calorie)
						} else {
							trans[sport[0].sport_name] = parseInt(data.train_calorie)
						}
					}

				}
			}
			if (Object.keys(trains).length === 0) {
				for (let label in trans) {
					trains.push({
						value: trans[label],
						name: label
					})
				}
			}

		}

	} else if (condition == 1) {
		let trans = {}
		let [monday, sunday] = getMondayAndSunday(time)
		let datas1 = await getData('sportTrain', {
			train_start: dbcmd.gt(new Date(monday)).and(dbcmd.lt(new Date(sunday))),
			user_id: store.getters.getToken
		})
		if (datas1.length > 0) {
			for (let data of datas1) {
				let sport = await getData('sport', {
					_id: data.train_id
				})
				if (sport.length > 0) {
					if (sport[0].sport_name in trans) {
						trans[sport[0].sport_name] += parseInt(data.train_calorie)
					} else {
						trans[sport[0].sport_name] = parseInt(data.train_calorie)
					}
				}

			}
			if (Object.keys(trains).length === 0) {
				for (let label in trans) {
					trains.push({
						value: trans[label],
						name: label
					})
				}
			}

		}
	} else {
		let trans = {}
		let [firstDay, lastDay] = getFirstDayAndLastDayOfMonth(time)
		let datas1 = await getData('sportTrain', {
			train_start: dbcmd.gte(new Date(firstDay)).and(dbcmd.lte(new Date(lastDay))),
			user_id: store.getters.getToken
		})
		if (datas1.length > 0) {
			for (let data of datas1) {
				let sport = await getData('sport', {
					_id: data.train_id
				})
				if (sport.length > 0) {
					if (sport[0].sport_name in trans) {
						trans[sport[0].sport_name] += parseInt(data.train_calorie)
					} else {
						trans[sport[0].sport_name] = parseInt(data.train_calorie)
					}
				}

			}
			if (Object.keys(trains).length === 0) {
				for (let label in trans) {
					trains.push({
						value: trans[label],
						name: label
					})
				}
			}

		}
	}
	return trains
}

const dbcmd = db.command
var ag = db.command.aggregate
async function getAvgW(firstDay, lastDay) {
	let datas = await db.collection('weighRecord').where({
		uploadTime: dbcmd.gte(firstDay).and(dbcmd.lte(lastDay)),
		user_Id: store.getters.getToken
	}).groupBy('user_Id').groupField('avg(weigh_value) as ag_w').get()
	return datas.result.data.length > 0 ? parseFloat(datas.result.data[0].ag_w).toFixed(2) : 0
}

async function getAvgH(firstDay, lastDay) {
	let datas = await db.collection('heightRecord').where({
		uploadTime: dbcmd.gte(new Date(firstDay)).and(dbcmd.lte(new Date(lastDay))),
		user_Id: store.getters.getToken
	}).groupBy('user_Id').groupField('avg(height_value) as ag_h').get()

	return datas.result.data.length > 0 ? parseFloat(datas.result.data[0].ag_h).toFixed(2) : 0
}
async function getHealthByCondition(condition, time) {
	let weighs = []
	let dates = []
	let heights = []
	if (condition == 0) {
		let [monday, sunday] = getMondayAndSunday(time)
		let datas1 = await db.collection('heightRecord').where({
			uploadTime: dbcmd.gt(new Date(monday)).and(dbcmd.lt(new Date(sunday))),
			user_Id: store.getters.getToken
		}).orderBy('uploadTime desc').get()
		let datas = await db.collection('weighRecord').where({
			uploadTime: dbcmd.gt(new Date(monday)).and(dbcmd.lt(new Date(sunday))),
			user_Id: store.getters.getToken
		}).orderBy('uploadTime desc').get()
		let tempdatas = datas.result.data
		let tempdatas1 = datas1.result.data
		for (let i = 1; i <= 7; i++) {
			let day = new Date(monday)
			day.setDate(day.getDate() + i).toLocaleString()
			dates.push(tranformDate(day.toLocaleDateString()))
			weighs.push(0)
			heights.push(0)
		}
		if (tempdatas.length > 0) {
			for (let temp of tempdatas) {
				let time = tranformDate(new Date(temp.uploadTime).toLocaleDateString())
				if (dates.includes(time)) {
					weighs[dates.indexOf(time)] = temp.weigh_value
				}
			}
		}
		if (tempdatas1.length > 0) {
			for (let temp of tempdatas1) {
				let time = tranformDate(new Date(temp.uploadTime).toLocaleDateString())
				if (dates.includes(time)) {
					heights[dates.indexOf(time)] = temp.height_value
				}
			}
		}

		for (let i = 0; i < 7; i++) {
			dates[i] = `${dates[i].split('-')[1]}/${dates[i].split('-')[2] }`
		}

	} else if (condition == 1) {
		let [year, month, day] = time.split('-')
		let [firstDay, lastDay] = getFirstDayAndLastDayOfMonth(time)
		for (var i = 1; i <= 4; i++) {
			if (i == 1) {
				dates.push(`第${i}周`)
				weighs.push(await getAvgW(new Date(firstDay), new Date(parseInt(year), parseInt(month), 7 *
					i)))
				heights.push(await getAvgH(new Date(firstDay), new Date(parseInt(year), parseInt(month), 7 *
					i)))
			} else if (i == 4) {
				dates.push(`第${i}周`)
				weighs.push(await getAvgW(new Date(parseInt(year), parseInt(month) - 1, 7 * (i -
					1)), new Date(lastDay)))
				heights.push(await getAvgH(new Date(parseInt(year), parseInt(
					month) - 1, 7 * (i -
					1)), new Date(lastDay)))
			} else {
				dates.push(`第${i}周`)
				weighs.push(await getAvgW(new Date(parseInt(year), parseInt(month) - 1, 7 * (i -
					1)), new Date(parseInt(year), parseInt(month), 7 * i)))
				heights.push(await getAvgH(new Date(parseInt(year), parseInt(month) - 1, 7 * (i -
					1)), new Date(parseInt(year), parseInt(month), 7 * i)))
			}
		}
	} else {
		let [year, month, day] = time.split('-')
		for (var i = 1; i <= 12; i++) {
			let [firstDay, lastDay] = getFirstDayAndLastDayOfMonth(new Date(parseInt(year), i - 1, 1))
			dates.push(`${i}月`)
			weighs.push(await getAvgW(new Date(firstDay), new Date(lastDay)))
			heights.push(await getAvgH(new Date(firstDay), new Date(lastDay)))
		}
	}
	return [dates, weighs, heights]
}
export const addData = insert
export const check = checkUnique
export const verify = update
export const remove = del
export const acquireData = getData
export const getCourseData = getCourse
export const getKGData = getSportKG
export const getSportData = getSport
export const getDynamicData = getDynamic
export const getUser = getUserInfo
export const getSportFavDate = getSportFav
export const getTrainDatas = getTrainByCondition
export const getHealthDatas = getHealthByCondition
export const tranformDateTime = tranformDate
export const compareDate = compareDates
export const getSportFavCommonData = getSportFavCommon
export const getTrainByDayData = getTrainByDay